import { log } from './logger'
import { FileInfo } from './types/FileInfo'

class FileTools {
  static openOneFile(cb: Function, accept: string = '') {
    let file = document.createElement('input')
    file.setAttribute('type', 'file')
    file.setAttribute('accept', accept)
    // file.setAttribute('multiple', 'multiple')
    // 文件改变事件
    file.addEventListener('change', () => {
      log.debug('文件选中变化', file.files)
      let fileinfo = {} as FileInfo
      if (file.files && file.files.length == 1) {
        const elefile = file.files[0]
        fileinfo = FileTools.getFileInfo(elefile)
        fileinfo.el = file
      }
      cb(fileinfo)
    })
    file.click()
  }
  static openFile(cb: Function, accept: string = '') {
    let file = document.createElement('input')
    file.setAttribute('type', 'file')
    file.setAttribute('accept', accept)
    file.setAttribute('multiple', 'multiple')
    // 文件改变事件
    file.addEventListener('change', () => {
      log.debug('文件选中变化', file.files)
      let files = new Array<FileInfo>()
      if (file.files) {
        for (let index = 0; index < file.files.length; index++) {
          const elefile = file.files[index]
          let result = FileTools.getFileInfo(elefile)
          result.el = file
          files.push(FileTools.getFileInfo(elefile))
        }
      }
      cb(files)
    })
    file.click()
  }

  static getFileInfo(file: File, fileinfo: FileInfo = {} as FileInfo): FileInfo {
    fileinfo.file = file
    fileinfo.size = file.size
    fileinfo.suffix = FileTools.getFileSuffix(file.name)
    fileinfo.type = FileTools.getFileType(file.type)
    fileinfo.name = file.name
    fileinfo.fulltype = file.type ? file.type : 'application/octet-stream'
    return fileinfo
  }

  static getFileSuffix(filename: string): string {
    let pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
      suffix = filename.substring(pos)
    }
    return suffix
  }
  static getFileType(type: string): string {
    if (!type) {
      return 'application/octet-stream'
    }
    let index = type.indexOf('/')
    return index > -1 ? type.substring(0, index) : type
  }

  static readImg(file: File, cb: any) {
    if (FileTools.getFileType(file.type) != 'image') {
      cb('')
      return
    }
    let reader = new FileReader()
    reader.addEventListener('load', () => {
      cb(reader.result)
    })

    reader.readAsDataURL(file)
  }

  static formatFileSize(filesize: number): string {
    log.debug('in filesize====>', filesize)
    if (filesize === 0) {
      return '0 B'
    }
    let k = 1024
    //单位值
    let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    let i = Math.floor(Math.log(filesize) / Math.log(k))
    //.toPrecision(3)
    return (filesize / Math.pow(k, i)).toFixed(1) + '' + sizes[i]
  }
}

export { FileTools as FileTools, FileTools as default }
